<template>
	<div class="phone-nav-bar"
	     :class="{'phone-nav-bar-load':load}"
			 id="softphonebar"
	     @click="initPhone">
		<Input ref="input"
		       :disabled="!invalid"
		       :placeholder="placeholderText"
		       class="phone-input"
		       :class="{'phone-input-error':loginError}"
		       @on-enter="inputCall"
		       v-model="number">
		<span slot="append">
			<Dropdown trigger="click">
				<span class="phone-button">
					<Icon class="icon-phone"
					      type="ios-telephone"></Icon>
					<i v-show="false"
					   class="ivu-icon ivu-icon-arrow-down-b ivu-select-arrow"></i>
				</span>
			</Dropdown>
			<layer v-model="numberCall"
			       class="keyboard"
			       :space="20"
						 :offsetX="-150"
						 :offsetY="-10"
						 @on-show="getCallLog()"
			       :transfer="false">
				<span class="number-call-btn"
				      @click.stop="numberCall=!numberCall"
				      slot="button">
					<Icon type="grid"
					      color="#fff"></Icon>
				</span>
				<div slot="body"
				     class="keyboard-container"
				     @click.stop>
					<div class="call-log">
						<p class="call-log-title">通&nbsp;话&nbsp;记&nbsp;录</p>
						<ul @click="listCall($event)" style="height: 80%;">
							<ScrollBar :vertical="true" :visible="true">
								<li class="call-log-item" :class="{'calling-icon': calling}" v-for="(item, index) in callLogList">
									<Icon type="ios-telephone log-success" v-if="item.connected === true"></Icon>
									<Icon type="ios-telephone log-failed" v-else-if="item.connected === false"></Icon>
									<Icon type="ios-telephone log-pending" v-else-if="item.connected === 'pending'"></Icon>
									<span class="call-num">{{item.phoneNum}}</span>
									<span class="call-times">{{item.times === 1 ? '' : '('+item.times+')'}}</span>
									<span class="call-renderTime">{{item.renderTime}}</span>
								</li>
								<li class="call-log-none" v-if="callLogList.length === 0" @click.stop>------ 暂无记录 ------</li>
							</ScrollBar>
						</ul>
					</div>
					<div class="number-call">
						<template v-for="(item, index) in numberKeys">
							<span v-if="item==='d'"
							      class="number-key"
							      @click.stop="removeNumber">
								<Icon type="close"></Icon>
							</span>
							<span v-else-if="item==='c'"
							      class="number-key"
							      @click.stop="inputCall">
								<Icon type="ios-telephone"></Icon>
							</span>
							<span v-else
							      class="number-key"
							      :key="index"
							      @click.stop="addNumber(item)">{{item}}</span>
						</template>
					</div>
				</div>
			</layer>
		</span>
		<span slot="prepend">
			<div class="box-text">
				<span v-if="loginError"
				      class="text-status b-red"
				      @click="phoneClose">
					<Icon type="information-circled"></Icon> 登录错误</span>
				<template v-else>
					<span v-show="phoneCloseShow || calling"
					      class="text-close b-red"
					      @click="phoneClose">
						<Icon type="close"></Icon> 挂断
					</span>
					<span v-show="calling"
					      class="text-status b-glaucous"
					      @click="phoneClose">
						<i class="ivu-load-loop ivu-icon ivu-icon-load-c"></i> 拨号中</span>
					<span v-show="!calling && !invalid"
					      class="text-status"
					      :class="stateClass">{{stateText}}</span>
					<span v-show="!calling && invalid"
					      class="text-status"
					      :class="stateClass">
						<Dropdown trigger="click"
						          @on-click="statusSelect">
							<span>
								<Icon v-if="stateIcon"
								      :type="stateIcon"></Icon> {{stateText}}
								<Icon type="arrow-down-b"></Icon>
							</span>
							<DropdownMenu slot="list">
								<DropdownItem name="0"
								              :selected="status.state==='stInvalid'">空闲</DropdownItem>
								<DropdownItem name="2"
								              :selected="status.state==='stRest'">小休</DropdownItem>
								<DropdownItem name="1"
								              :selected="status.state==='stBusy'">忙碌</DropdownItem>
							</DropdownMenu>
						</Dropdown>
					</span>
				</template>
			</div>
			<span class="text-time">
				{{status.peerTime}}
			</span>
		</span>
		</Input>
	</div>
</template>
<script>
import $ from '@/common';
import $time from '@/common/time';
import Phone from './phone';
import './pages.css';
import layer from '@/element/layer';
import ScrollBar from '@/element/scrollbar'
export default {
	name: 'phoneTool',
	data() {
		return {
			number: '',
			//读取状态
			load: false,
			//是否回调
			hasCallBack: false,
			//电话接通状态
			connect: false,
			//拨打中状态(等待软电话响应并进入dialing阶段，webcall返回状态）
			calling: false,
			//软电话拨打状态
			dialing: false,
			//登录错误状态
			loginError: false,
			// historyList: [],
			status: {
				peerTime: '00:00:00',
				state: null,
			},
			numberCall: false,
			numberKeys: ['7', '8', '9', '4', '5', '6', '1', '2', '3', 'd', '0', 'c'],
			callLogMax: 100,
			log: {},
			callLogListSource: [],
		};
	},
	components: {
		layer,
		ScrollBar
	},
	computed: {
		invalid() {
			var v = ['stInvalid', 'stBusy', 'stRest', 'pauseUnlink'].indexOf(this.status.state) > -1;
			if (v) {
				this.$nextTick(() => {
					this.$refs.input.focus();
				});
			} else {
				this.calling = false;
			}

      if (this.status.state === 'ready') {
        return true;
      }
			return v;
		},
		placeholderText() {
			if (this.load) {
				return '请输入号码,按回车拨打';
			} else {
				if (this.loginError) {
					this.number = null;
					return '登录错误，请点击重试';
				} else {
					return '点击加载软电话';
				}
			}
		},
		stateSetting() {
			return (
				Phone.statusList[this.status.state] || {
					text: '就绪',
					class: 'gray',
				}
			);
		},
		stateText() {
			return this.stateSetting.text;
		},
		stateIcon() {
			return this.stateSetting.icon;
		},
		stateClass() {
			return {
				['b-' + this.stateSetting.class]: true,
			};
		},
		phoneCloseShow() {
      if (this.load) {
        return this.status.state === 'stDialing' || this.status.state === 'outRinging';
      }
      return this.load;
		},
		callLogList() {
			if (!this.callLogListSource || this.callLogListSource.length === 0) return []
			// 复制源数据操作避免污染
			let copyList = $.copy(this.callLogListSource)
			// 根据时间戳排序
			copyList.sort((a, b) => {
				return b.timestamp - a.timestamp
			})
			// 制造renderTime
			copyList.forEach((item) => {
				item.renderTime = $time.getTimeInterval(item.timestamp)
				item.times = 1
			})
			// 去重并记录次数
			let parseList = [copyList[0]]
			copyList.forEach((item,index) => {
				if (index === 0) {
					return
				}
				let sameNum = item.phoneNum === parseList[parseList.length - 1].phoneNum
				let sameConnected = item.connected === parseList[parseList.length - 1].connected
				if (!sameNum || (sameNum && !sameConnected)) {
					parseList.push(item)
				} else {
					parseList[parseList.length - 1].times++
				}
			})
			return parseList
		}
	},
	watch: {
		'status.state': function(v) {
      if (v === 'stDialing') {
        window.daledianhuaxianshimorenzhi = true;
        window.__uniquerow_data = window.uniquerow_data;
        window.uniquerow_data = undefined;
        this.successCallback();
      }

			if (this.dialing) {
				//由拨打中改变状态时进行回调，并清空回调缓存

				if (v === 'answered') {
					if (this.successCallback) {
            window.daledianhuaxianshimorenzhi = true;
            window.__uniquerow_data = window.uniquerow_data;
            window.uniquerow_data = undefined;
						this.successCallback();
					}
				} else {
					if (this.errorCallback) {
            window.uniquerow_data = undefined;
            window.daledianhuaxianshimorenzhi = false;
						this.errorCallback();
					}
				}
				// this.successCallback = null;
				// this.errorCallback = null;
			}

      if (v === 'stDialing' || v === 'outRinging') {
        this.dialing = true;
      } else {
        this.dialing = false;
      }
		},
		calling(v) {
			if (!v) {
				this.log = {}
			}
			this.saveCallLog()
		},
		load(v) {
			if (v && !this.loginError) {
				this.loginError = false;
			}
		},
	},
	methods: {
		listCall(e) {
			// 阻止重复拨打
			if (this.calling) return
      let target = e.target;
			while (target.tagName.toLowerCase() !== 'ul') {
          if (target.tagName.toLowerCase() === 'li') {
              this.number = target.querySelector('span.call-num').innerHTML.trim();
              break;
          }
          target = target.parentNode;
      }
			this.callNumber(this.number, this.callSuccessCb, this.callFailedCb)
		},
		callSuccessCb() {
			// 拨打成功时，更正 callLogListSource 数据，再重新存入 localStorage
			this.callLogListSource[0].connected = true
			console.log('successCB')
			this.saveCallLog()
		},
		callFailedCb() {
			// 拨打失败时, 更正 callLogListSource 数据，再重新存入 localStorage
			this.callLogListSource[0].connected = false
			// console.log('failedCb')
			this.saveCallLog()
		},
		setCallLog() {
			this.callLogListSource.unshift(this.log)
			if (this.callLogListSource.length > this.callLogMax) {
				this.callLogListSource.pop()
			}
		},
		saveCallLog() {
			let copyList = $.copy(this.callLogListSource)
			// 修复可能出现的错误数据（入使用时断网等缘故造成存入了错误数据）
			copyList.forEach(item => {
				if (item.connected === 'pending') {
					item.connected = false
				}
			})
			localStorage.setItem('callLog', JSON.stringify(copyList))
		},
		getCallLog() {
			let list = JSON.parse(localStorage.getItem('callLog'))
			if (!list) return
			this.callLogListSource = list
			// inpuCall 时，打开通话记录正确显示
			if (this.log.connected) {
				this.callLogListSource[0].connected = this.log.connected
			}
		},
		//获取拨号数据
		getCallData() {},
		statusSelect(state) {
			state = parseInt(state);
			window.phone.setBusy(state === 0, state);
		},
		phoneClose() {
			if (this.calling) {
				this.calling = false;
				//this.load = false;
        if (Phone.getIsTky()) {
          Phone.hangup();
        } else {
          window.phone.hangup();
        }
				setTimeout(() => {
					//Phone.destroy();
				}, 1000);
			} else {
        if (Phone.getIsTky()) {
          Phone.hangup();
        } else {
          window.phone.hangup();
        }
			}
		},
		callNumber(num, success, error, isInputCall) {
      if (num) {
        this.__success = success;
        this.__error = error;
        !isInputCall ? (this.number = `${num.substr(0,3)}****${num.substr(7)}`) : (this.number = num);
        this.realNumber = num;
      }

      if (!this.load) {
        this.initPhone().then(() => {
          this.callNumberProcess(num, success, error);
        });
      } else {
        this.callNumberProcess(num, success, error);
        this.callLogListSource
      }
      // 只要拨号，就制造一条记录，connected为null标识不知道是否接通
      this.log = {
        phoneNum: this.number,
        timestamp: Date.parse(new Date()),
        connected: 'pending'
      }
      // 并记入 callLogListSource 和 localStorage
      this.setCallLog()
			// 然后会在传入的 success 和 error 回调中修改 connected 然后重新记入 callLogListSource 和 localStorage
			// 这样只要拨号就都能记入callLog了，并且能够正确记录状态
		},
		callNumberProcess(num, success, error) {
			this.calling = true;
			this.load = true;
			this.$nextTick(() => {
				this.$refs.input.focus();
			});
			this.successCallback = success;
			this.errorCallback = error;
			Phone.call(this.realNumber, success, error);
      this.__success = undefined;
      this.__error = undefined;
		},
		inputCall() {
			this.callNumber(this.number, this.callSuccessCb, this.callFailedCb, true);
		},
		setData(code, data) {
			this.status[code] = data;
		},
		loginToError(res) {
			this.calling = false;
			this.load = false;
			this.loginError = true;
		},
		initPhone() {
			this.loginError = false;
			if (this.load) return;
			var vm = this;
			// 通过切入组件方法实现后去状态的数值
			return Phone.init().then(() => {
        if (Phone.getIsTky()) {
          return false;
        }
				var _afterPhone = window.icallcenter.logon.afterPhone;
				window.icallcenter.logon.afterPhone = (...arg) => {
					//调用完成状态
					vm.load = true;
					window.icallcenter.onError = res => {
						this.calling = false;
						vm.$Message.error(res);
					};
					_afterPhone(...arg);
					//改变 softphoneBar.onChangeState
					var softphoneBar = window.softphoneBar;
					var _showTimer = softphoneBar._showTimer;
					softphoneBar._showTimer = function() {
						_showTimer.call(this);
						var i = this;
						i._peerSecond = '1';
						i._peerMinute = '0';
						i._peerHour = '0';
						if (i._peerCalculagraph != null) {
							window.clearInterval(i._peerCalculagraph);
						}
						i._peerCalculagraph = window.setInterval(function() {
							var time =
								(i._peerHour < 10 ? '0' + i._peerHour : i._peerHour) +
								':' +
								(i._peerMinute < 10 ? '0' + i._peerMinute : i._peerMinute) +
								':' +
								(i._peerSecond < 10 ? '0' + i._peerSecond : i._peerSecond);
							//设置当前时间状态
							vm.status.peerTime = time;
							i._peerSecond++;
							if (i._peerSecond === 60) {
								i._peerMinute++;
								i._peerSecond = 0;
							}
							if (i._peerMinute === 60) {
								i._peerHour++;
								i._peerMinute = 0;
							}
						}, 1000);
					};
					//设置状态显示
					var onChangeState = softphoneBar.onChangeState;
					softphoneBar.onChangeState = function(d) {
						onChangeState.call(this, d);
						vm.status.state = d;
					};
					vm.$nextTick(() => {
						Phone.complete(vm.successCallback, vm.errorCallback);
						vm.$refs.input.focus();
					});
				};
			});
		},
		addNumber(item) {
			this.number = (this.number + item).trim();
		},
		removeNumber() {
			this.number = this.number.slice(0, this.number.length - 1);
		},
    TKYCallback(data) {
      const code = data.code;
      if (data.code === 0 && data.msg === '账号绑定成功') {
        this.load = true;
        Phone.isLoad = true;
        this.callNumber(this.number, this.__success, this.__error);
      }
      switch (code) {
        case 1:
          this.loginError = true;
          window.LinkErrorHandler(data.msg || '登录失败');
          break;
        // case 2:
        //   window.LinkErrorHandler('挂机失败');
        //   break;
        case 6:
          data.msg !== 'NORMAL_CLEARING' && window.LinkErrorHandler('外呼失败');
          break;
        // case 17:
        //   window.LinkErrorHandler('保持通话失败');
        //   break;
        // case 18:
        //   window.LinkErrorHandler('保持取消失败');
        //   break;
        default:
          break;
      }
    },
    _showTimerTky() {
      var i = this;
      i._peerSecond = '1';
      i._peerMinute = '0';
      i._peerHour = '0';
      if (i._peerCalculagraph != null) {
        window.clearInterval(i._peerCalculagraph);
      }
      i._peerCalculagraph = window.setInterval(function() {
        var time =
          (i._peerHour < 10 ? '0' + i._peerHour : i._peerHour) +
          ':' +
          (i._peerMinute < 10 ? '0' + i._peerMinute : i._peerMinute) +
          ':' +
          (i._peerSecond < 10 ? '0' + i._peerSecond : i._peerSecond);
        //设置当前时间状态
        i.status.peerTime = time;
        i._peerSecond++;
        if (i._peerSecond === 60) {
          i._peerMinute++;
          i._peerSecond = 0;
        }
        if (i._peerMinute === 60) {
          i._peerHour++;
          i._peerMinute = 0;
        }
      }, 1000);
    }
	},

	created() {
		window.SetWebCall = (...arg) => {
			return this.setData(...arg);
		};

    /// 天客云回调函数
    window.__TKYCallback = this.TKYCallback; // 集合所有操作回调函数
    window.cbThisStatus = (data) => {
      if (data.eventName === 'outRinging') {
        this._showTimerTky();
      }
      if (data.eventName === 'onlineUnlink') {
        this.callSuccessCb()
        window.clearInterval(this._peerCalculagraph);
        this.$nextTick(() => {
          this.status.peerTime = '00:00:00';
        });
      }
      this.setData('state', data.eventName);
    };

		$.webcall = this;
		this.getCallLog()
	},
	mounted() {},
};
</script>
<style lang="less">
body.has-modal .phone-nav-bar.phone-nav-bar-load {
	position: fixed;
	top: 0px;
	right: 5px;
	z-index: 10000;
	.phone-input {
		.ivu-input-group-append,
		.ivu-input-group-prepend {
			border-color: transparent;
		}
	}
}

.phone-nav-bar {
	.phone-input {
		.phone-button {
			margin: -8px;
			padding: 8px;
		}
		.ivu-input-group-append,
		.ivu-input-group-prepend {
			color: #fff;
			cursor: pointer;
			background-color: #55d795;
			/*border-color: #48db91;*/
			&:hover {
				background: #7ce793;
			}
			.ivu-dropdown .ivu-select-dropdown {
				right: 0 !important;
				width: auto !important;
				left: auto !important;
				top: 27px !important;
			}
			.text-status {
				.ivu-dropdown .ivu-select-dropdown {
					top: 13px !important;
				}
				.ivu-dropdown-menu {
					min-width: 48px;
					.ivu-dropdown-item {
						font-size: 12px;
						padding: 4px;
						.active {
							color: #fff;
							background: rgba(45, 140, 240, 0.9);
						}
					}
				}
			}
		}
		.ivu-input {
			&:disabled {
				cursor: pointer;
			}
			/*border-color: #48db91;*/
		}
		.ivu-select-arrow {
			margin-right: -2px;
			top: -2px;
			position: relative;
			margin-left: 0px;
			right: auto;
			left: auto;
			font-size: 12px;
			color: #fff;
		}
		.icon-phone {
			font-size: 16px;
		}
		.box-text {
			margin-right: 4px;
			position: absolute;
			right: 52px;
			z-index: 4;
			top: 10px;
			font-size: 12px;
			color: #fff;
			> span {
				padding: 3px 5px;
				border-radius: 4px;
				margin-left: 4px;
			}
		}

		.ivu-input:focus {
			outline: 0;
			box-shadow: none;
		}
	}
}

.phonebar {
	z-index: 100;
	position: relative;
	margin-top: -12px;
	.phone-page {
		border: none;
		overflow: visible;
		padding: 0;
		/*height: 200px;*/
	}

	.barBox {
		margin-top: 10px;
	}
	.ivu-btn {
		width: 80px;
	}
	.bar-status {
		.ivu-btn {
			width: 83px;
		}
	}
	.peerTimeState {
		padding: 6px;
		text-align: center;
	}
	.softphone_timer {
		float: none;
		clear: both;
		display: block;
	}
}
.keyboard {
	display: inline-block;
}
.number-call-btn {
	display: block;
	cursor: pointer;
	padding: 4px 7px;
	background-color: #55d795;
}
.keyboard-container{
	background-color: #fff;
	border-radius: 4px;
	display: flex;
	width: 400px;
	height: 228px;
	overflow: hidden;
	flex-wrap: wrap;
	.call-log{
		width: 230px;
		background-color: rgb(73, 74, 95);
		margin-right: 2px;
		border-radius: 4px;
		cursor: inherit;
		.call-log-title{
			padding: 14px 0 10px 0;
			line-height: 10px;
			font-size: 15px;
		}
		.call-log-none{
			padding: 70px 0 0 0;
			line-height: 10px;
			font-size: 14px;
			color: #80848f;
		}
		.call-log-item{
			line-height: 10px;
			font-size: 16px;
			padding: 2px 6px 2px 0;
			cursor: pointer;
			transition: 0.3s all;
			&:hover{
				color: #2d8cf0;
				.call-renderTime{
					color: #2d8cf0;
				}
			}
			.call-num{
				display: inline-block;
				width: 100px;
			}
			.call-times{
				display: inline-block;
				text-align: left;
				width: 30px;
			}
			.call-renderTime{
				display: inline-block;
				width: 60px;
				text-align: right;
				font-size: 14px;
				color: #80848f;
			}
			.log-success{
				color: #19be6b;
			}
			.log-failed{
				color: #ed3f14;
			}
			.log-pending{
				color: #ff9900;
			}
		}
	}
}
.number-call {
	border-radius: 4px;
	display: flex;
	width: 166px;
	padding: 5px;
	flex-wrap: wrap;
	background-color: rgb(73, 74, 95);
	.number-key {
		display: block;
		width: 40px;
		height: 40px;
		margin: 6px;
		text-align: center;
		line-height: 40px;
		border: 2px solid #aaa;
		border-radius: 5px;
		cursor: pointer;
		color: #fff;
		font-size: 16px;
		user-select: none;
		transition: 0.3s all;
		&:hover {
			border-color: #2d8cf0;
			color: #2d8cf0;
		}
		&:active {
			border-color: #2d8cf0;
			color: #2d8cf0;
			position: relative;
			top: 1px;
		}
	}
}
</style>
